/**   
 * Copyright © 2019 eSunny Info. Tech Ltd. All rights reserved.
 * 
 * 功能描述：
 * @Package: com.seccloud.tencentcloudapi.ext.vpc 
 * @author: Yannis   
 * @date: 2019年9月9日 下午6:06:47 
 */
package com.vpc;


import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.http.HttpResponse;
import com.tce.TceUtils;
import com.tce.tsfcluster.TsfClient;

public class VpcUtils {

	public static Subnet getFitSubNetByVpc(String vpcId, String region, String zone) throws Exception {
		DescribeSubnetsResponse response = getSubnetByVpc(vpcId, region, zone);
		Subnet[] subNets = response.getData();
		if(subNets == null || subNets.length == 0) {
			return null;
		}
		// get the sub net from the range
		for(Subnet subnet: subNets) {
			if(subnet.getAvailableIPNum() == 0) {
				continue;
			}
			return subnet;
		}
		return null;
	}
	
	private static DescribeSubnetsResponse getSubnetByVpc(String vpcId, String region, String zone) throws Exception {
		String actionName = "DescribeSubnetEx";
		JSONObject body = new JSONObject();
		body.put("vpcId", vpcId);
		String vpcUrl = "vpc.api2.tce.piccit.com.cn/v2/index.php";
		try {
			TreeMap<String, Object> paramTree = TceUtils.fillTsfParam(body, actionName, region, vpcUrl, "GET", "2017-03-12");
			TreeMap<String, String> headers = TceUtils.fillHttpHead(vpcUrl);
			String parasStr = TceUtils.getParamForBody(paramTree);
			System.out.println("=====" + "https://" + vpcUrl + "?" + parasStr);
			HttpResponse resp = new TsfClient().get("https://" + vpcUrl + "?" + parasStr, headers);
			if(resp.getStatusCode() == 200) {
				if(resp.getBody().indexOf("Error") >= 0) {
					throw new Exception("Describe Vpc Failed."+resp.getBody());
				}
				JSONObject bodyJson = JSONObject.parseObject(resp.getBody());
				DescribeSubnetsResponse response = bodyJson.toJavaObject(DescribeSubnetsResponse.class);
				if(bodyJson.getInteger("code") != 0) {
					throw new Exception("Describe Vpc Failed."+resp.getBody());
				}
				return response;
			}else {
				throw new Exception("Describe Vpc Failed."+resp.toString());
			}
		} catch (Exception e) {
			throw e;
		}
	}
}
